// connect的参数:
// 参数一: 函数
// 参数二: 函数
// 返回值: 函数 => 高阶组件
import { PureComponent } from "react";
import { StoreContext } from './StoreContext'

export function connect(mapStateToProps, mapDispatchToProps, store) {
  // 高阶组件: 函数
  return function(WrapperComponent) {
    class NewComponent extends PureComponent {
      /**
        props参数: WrapperComponent组件的props
        context参数: StoreContext组件的context
       */
      constructor(props, context) {
        super(props)

        this.state = mapStateToProps(context.getState())
      }

      componentDidMount() {
        // 订阅
        this.unsubscribe = this.context.subscribe(() => {
          this.setState(mapStateToProps((this.context.getState())))
        })
      }

      componentWillUnmount() {
        this.unsubscribe() // 取消订阅
      }

      render() {
        const stateObj = mapStateToProps(this.context.getState())
        const dispatchObj = mapDispatchToProps(this.context.dispatch)

        return <WrapperComponent {...this.props} {...stateObj} {...dispatchObj} />
      }
    }

    NewComponent.contextType = StoreContext
    return NewComponent
  }
}